package com.xindaoapp.happypet.view;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

public class Circle extends View {
    Paint paint;
    private float r = 100;// 圆的半径
    private int a = 0;// 标记x轴，用于自增
    private float rate = 1.5f;// 比率，y的跳动幅度

    private Timer timer1;
    private TimerTask task1;


    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            invalidate();
        }
    };


    // 最一开始 Start ！！！
    public Circle(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 汗。。。
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    // 开始first
    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(0xff00fcff);
        paint.setAlpha(0xff);
        paint.setStrokeWidth(10);
        paint.setStyle(Style.FILL);


    }

    public void startAnim() {

        // 重置
        r = 100;// 圆的半径
        a = 0;// 标记x轴，用于自增
        rate = 1.5f;// 比率，y的跳动幅度

        timer1 = new Timer();
        task1 = new TimerTask() {
            @Override
            public void run() {
                if (rate > 0) {
                    a += 5;// x轴
                    // 0.25f是振幅的比率，r缩小，这个也要缩小
                    float tempY = ((float) Math.cos((a * Math.PI) / 180) * 10) * 0.25f;// y轴,用于判断跳动了几个周期,2.5倍，之前是10倍
                    // System.out.println("tempY:"+tempY);
                    if (tempY == 2.5f) {// 判断第几个周期
                        rate -= 0.3; // 缩小振幅比率
                    }
                    r += tempY * rate;// 原始振幅再缩小比率 注意！！！下方的时间同样关键试验过30,15,10,5，越快越看不出来
                    // System.out.println(r);
                }
                handler.sendEmptyMessage(0);
            }

        };
        timer1.schedule(task1, 0, 5);
        handler.notify();
    }

    // 绘制second
    @Override
    protected void onDraw(final Canvas canvas) {
        int a = getWidth() / 2;
        int b = getHeight() / 2;
        canvas.drawCircle(a, b, r, paint);

    }

}
